package client

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/sirupsen/logrus"
	"github.com/urfave/cli/v2"
	"io/ioutil"
	"os"
	"path"
	"ycontainer/container"
)

func LogsAction(context *cli.Context) error {
	if context.Args().Len() < 1 {
		return fmt.Errorf("missing container name")
	}

	containerName := context.Args().First()

	fullFilePath := path.Join(container.YcontainerRoot, "containers", containerName, container.DefaultLogFileName)

	file, _ := os.Open(fullFilePath)

	content, err := ioutil.ReadAll(file)
	if err != nil {
		logrus.Errorf("Read file %s err: %v", fullFilePath, err)
	}

	fmt.Fprintf(os.Stdout, string(content))
	return nil
}

func printLogs(fullFilePath string) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		logrus.Errorf("new watcher failed: %v", err)
	}
	defer watcher.Close()

	done := make(chan bool)
	go func() {
		defer close(done)
		for {
			select {
			case event, ok := <-watcher.Events:
				if !ok {
					return
				}
				logrus.Infof("%s %s", event.Name, event.Op)
			case err, ok := <-watcher.Errors:
				if !ok {
					return
				}
				logrus.Errorf("error: %v", err)
			}
		}
	}()
	err = watcher.Add(fullFilePath)
	if err != nil {
		logrus.Errorf("add failed: %v", err)
	}

	<-done
}
